package com.msmall.community.klg.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.msmall.base.cache.CacheFactory;
import com.msmall.base.pager.PaginationSupport;
import com.msmall.base.service.impl.BaseManagerImpl;
import com.msmall.base.util.ConstantDB;
import com.msmall.base.util.Constants;
import com.msmall.community.common.CascadeCollection;
import com.msmall.community.common.util.ContentUtil;
import com.msmall.community.common.util.FilterCharsUtil;
import com.msmall.community.dpt.model.Segment;
import com.msmall.community.klg.dao.ArticleDao;
import com.msmall.community.klg.model.Article;
import com.msmall.community.klg.model.ArticleReply;
import com.msmall.community.klg.model.SegmentArticle;
import com.msmall.community.klg.service.ArticleManager;
import com.msmall.community.klg.util.KLGUtil;
import com.msmall.community.user.model.UserInfo;
import com.msmall.community.user.service.UserManager;

public class ArticleManagerImpl extends BaseManagerImpl<Article, Long> implements ArticleManager{
	
	private static final Log log = LogFactory.getLog(ArticleManagerImpl.class);
	
	private ArticleDao articleDao;

	private UserManager userManager;
	
	public void setArticleDao(ArticleDao articleDao) {
		this.articleDao = articleDao;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	/**
	 * 创建新的文章
	 * @param article
	 * @param segid 文章分类ID
	 * @param userid creator
	 * @param userAgentType
	 * @return
	 */
	public Article saveArticle(Article article, Long segid, Long userid, String userAgentType) throws Exception{
		try{
			UserInfo user = userManager.getByUserid(userid);
			Date date = new Date();
			String content = article.getContent();
			String[] urls =KLGUtil.writeArticlemFile(content, date, userAgentType);
			article.setFilePath(urls[0]);
			article.setFileName(urls[1]);
			article.setFileExt(urls[2]);
			article.setFileFlag(Constants.USER_AGENT_TYPE_HTML.equals(userAgentType)?Constants.FILE_CREATED_FLAG_HTML:Constants.FILE_CREATED_FLAG_WML);
			
			if(StringUtils.isEmpty(article.getContentAbstract())){
				int size = KLGUtil.getContentAbstractChars();
				content = ContentUtil.escapeHtmlTags(content);
				if(content.length() > size){
					article.setContentAbstract(content.substring(0, size));
				}else{
					article.setContentAbstract(content);
				}
			}
			article.setUserId(userid);
			article.setNickname(user.getNickname());
			article.setCreateTime(date);
			article.setLastModifyTime(date);
			article.setLastThreadTime(date);
			article.setClickAmount(0);
			article.setElite(ConstantDB.UNELITE);
			article.setEnabled(ConstantDB.AVALIABLE);
			article.setReply(ConstantDB.REPLY);
			article.setSource(Constants.USER_AGENT_TYPE_WML.equalsIgnoreCase(userAgentType)? ConstantDB.USER_AGENT_TYPE_WML :ConstantDB.USER_AGENT_TYPE_HTML);
			article.setTop(ConstantDB.UNTOP);
			article = articleDao.save(article);
			
			SegmentArticle sa = new SegmentArticle();
			sa.setArticleid(article.getArticleid());
			sa.setSegmentid(segid);
			articleDao.saveObject(sa);
			
			return article;
		}catch(Exception e){
			log.debug(e);
			throw e;
		}
	}

	public void deleteArticle(Long articleid) throws Exception{
		
	}
	
	public Article getArticle(Long articleid) throws Exception{
		try{
			return (Article) articleDao.get(Article.class, articleid);
		}catch(Exception e){
			log.debug(e);
			throw e;
		}
	}
	/**
	 * 通过文章ID 查找文章分类
	 * @param articleid
	 * @return
	 * @throws Exception
	 */
	public SegmentArticle getSegmentByArticleid(Long articleid) throws Exception{
		return articleDao.getSegmentByArticleid(articleid);
	}
	/**
	 * 通过文章ID 查找文章以及文章分类<br/>
	 * object[0] = Article Object[1]=SegmentArticle
	 * @param articleid
	 */
	public Object[] getArticleAndSegmentByArticle(Long articleid) throws Exception{
		try{
			return articleDao.getArticleAndSegmentByArticle(articleid);
		}catch(Exception e){
			log.debug(e);
			throw e;
		}
	}
	/**
	 * 获得文章分类下的所有文章
	 * 通过创建时间排序
	 * 所有的都选出 enabled or not
	 * userid 每页的查询数量根据//没有实现
	 * children : 包含此segment下的多有子segment
	 */
	public void getArticlePaginationBySegment(PaginationSupport page, Long userid, Long segid, boolean children) throws Exception{
		try{
			StringBuffer buffer = new StringBuffer();
			buffer.append("select t from Article t, SegmentArticle sa where t.articleid=sa.articleid ");
			if(children){
				CascadeCollection<Segment> cs = (CascadeCollection<Segment>) CacheFactory.getInstance().getCache(Constants.CACHE_NAME_COMMON).get(Constants.CACHE_KEY_SEGMENT_CASCADECOLLECTION);
				CascadeCollection<Segment> current = cs.getAllDatas().get(segid);
				buffer.append(" and ( sa.segmentid =").append(segid);
				for(CascadeCollection<Segment> child : current.getChildren()){
					buffer.append(" or sa.segmentid=").append(child.getCurrent().getSegmentid());
				}
				buffer.append(" )");
			}else{
				buffer.append(" and sa.segmentid =").append(segid);
			}
			buffer.append(" order by t.createTime asc");
			
			page.setQueryString(buffer.toString());
			articleDao.getPagination(page);
		}catch(Exception e){
			log.debug(e);
			throw e;
		}
	}
	/**
	 * 获得文章分类下的所有文章
	 * 通过创建时间排序
	 * 所有的都选出 enabled or not
	 * userid 每页的查询数量根据//没有实现
	 */
	public void getArticlePaginationBySegment(PaginationSupport page, Long userid, Long segid) throws Exception{
		try{
			page.setClazz(Article.class);
			
			String queryString = "select t from Article t, SegmentArticle sa where t.articleid=sa.articleid and sa.segmentid = " + segid;
			queryString += " order by t.createTime asc";
			page.setQueryString(queryString);
			articleDao.getPagination(page);
		}catch(Exception e){
			log.debug(e);
			throw e;
		}
	}
	/**
	 * 通过时间比较 获得当前文章的前几篇文章<br/>
	 * sameSeg是否在同一个文章分类下比较
	 */
	public List<Article> getPreArticle(Long articleid, Long segid, boolean sameSeg,int amount) throws Exception{
		try{
			PaginationSupport page = new PaginationSupport();
			StringBuffer buffer = new StringBuffer();
			if(sameSeg){
				buffer.append("select a from Article a, SegmentArticle sa where sa.segmentid=")
				.append(segid)
				.append(" and sa.articleid=a.articleid and a.createTime<(select b.createTime from Article b where b.articleid=")
				.append(articleid)
				.append(") order by a.createTime DESC ");
//				queryString="select a from Article a, SegmentArticle sa where sa.segmentid="+segid
//				+" and sa.articleid=a.articleid and a.createTime<(select b.createTime from Article b where b.articleid="+articleid+") order by a.createTime DESC ";
			}else{
				buffer.append("select a from Article a where a.createTime<(select b.createTime from Article b where b.articleid=")
					.append(articleid)
					.append(")");
//				queryString = "select a from Article a where a.createTime<(select b.createTime from Article b where b.articleid="+articleid+") order by a.createTime DESC ";
			}
			page.setQueryString(buffer.toString());
			page.setAutoCount(false);
			page.setPageSize(amount);
			articleDao.getPagination(page);
			return page.getItems();
		}catch(Exception e){
			log.debug(e);
			throw e;
		}
	}
	/**
	 * 通过时间比较 获得当前文章的后几篇文章<br/>
	 * sameSeg是否在同一个文章分类下比较
	 */
	public List<Article> getNextArticle(Long articleid, Long segid, boolean sameSeg,int amount) throws Exception{
		try{
			PaginationSupport page = new PaginationSupport();
			StringBuffer buffer = new StringBuffer();
			if(sameSeg){
				buffer.append("select a from Article a, SegmentArticle sa where sa.segmentid=")
				.append(segid)
				.append(" and sa.articleid=a.articleid and a.createTime>(select b.createTime from Article b where b.articleid=")
				.append(articleid)
				.append(") order by a.createTime ASC ");
//				queryString="select a from Article a, SegmentArticle sa where sa.segmentid="+segid
//				+" and sa.articleid=a.articleid and a.createTime>(select b.createTime from Article b where b.articleid="+articleid+") order by a.createTime ASC ";
			}else{
				buffer.append("select a from Article a where a.createTime>(select b.createTime from Article b where b.articleid=")
				.append(articleid)
				.append(")");
//				queryString = "select a from Article a where a.createTime>(select b.createTime from Article b where b.articleid="+articleid+") order by a.createTime ASC ";
			}
			page.setQueryString(buffer.toString());
			page.setAutoCount(false);
			page.setPageSize(amount);
			articleDao.getPagination(page);
			return page.getItems();
		}catch(Exception e){
			log.debug(e);
			throw e;
		}
	}
	
	/**
	 * 获得文章分类下的所有文章
	 * 通过创建时间排序
	 * 只选出enabled
	 * userid 每页的查询数量根据//没有实现
	 */
	public void getEnabledArticlePaginationBySegment(PaginationSupport page, Long userid, Long segid) throws Exception{
		try{
			page.setClazz(Article.class);
			
			String queryString = "select t from Article t, SegmentArticle sa where t.enabled="+ConstantDB.AVALIABLE+" and t.articleid=sa.articleid and sa.segmentid = " + segid;
			queryString += " order by t.createTime asc";
			page.setQueryString(queryString);
			articleDao.getPagination(page);
		}catch(Exception e){
			log.debug(e);
			throw e;
		}
	}
	/**
	 * 获得创建人某个文章分类下的所有文章。如果segmentid==null，默认选出所有的
	 * 通过创建时间排序
	 * 只选出enabled
	 * creator 创建人。(每页的查询数量根据//没有实现)
	 */
	public void getEnabledArticlePaginationBySegmentCreator(PaginationSupport page, Long creator, Long segid) throws Exception{
		try{
			page.setClazz(Article.class);
			
			String queryString = "select t from Article t, SegmentArticle sa where t.enabled="+ConstantDB.AVALIABLE+" and t.articleid=sa.articleid and sa.segmentid = " + segid + " and t.userId=" + creator;
			queryString += " order by t.createTime asc";
			page.setQueryString(queryString);
			articleDao.getPagination(page);
		}catch(Exception e){
			log.debug(e);
			throw e;
		}
	}
	
	public ArticleReply getArticleReply(Long replyId) throws Exception{
		try{
			return (ArticleReply) articleDao.get(ArticleReply.class, replyId);
		}catch(Exception e){
			log.debug(e);
			throw e;
		}
	}

	/**
	 * 创建新的文章分类
	 * @param userid creator
	 * @param userAgentType
	 * @return
	 */
	public ArticleReply saveArticleReply(ArticleReply reply, Long userid, String userAgentType) throws Exception{
		try{
			UserInfo user = userManager.getByUserid(userid);
			reply.setCreateTime(new Date());
			reply.setNickname(user.getNickname());
			reply.setUserId(userid);
			reply.setEnabled(ConstantDB.AVALIABLE);
			reply = (ArticleReply) articleDao.saveObject(reply);
			return reply;
		}catch(Exception e){
			log.debug(e);
			throw e;
		}
	}
	/**
	 * 更新
	 */
	public void updateArticleReply(ArticleReply reply, Long userid, String uat) throws Exception{
		
	}
	public void deleteArticleReply(Long replyId) throws Exception{
		
	}
	
	/**
	 * 获得某文章的分类.enabed or not都选出
	 * @param page
	 * @param userid 当前登录系统的用户，用于分页的PAGESIZE
	 * @param articleid 文章ID
	 */
	public void getArticleReplyPaginationByArticle(PaginationSupport page, Long userid, Long articleid) throws Exception{
		try{
			page.setClazz(ArticleReply.class);
			
			String queryString = "from ArticleReply t where t.articleid = " + articleid;
			queryString += " order by t.createTime asc";
			page.setQueryString(queryString);
			articleDao.getPagination(page);
		}catch(Exception e){
			log.debug(e);
			throw e;
		}
	}
	/**
	 * 验证article TITLE
	 * @return 1:正常；2字符太少；3字符太多;4含有非法字符
	 */
	public int validateArticleTitle(String title){
		int titleOK = KLGUtil.checkArticleTitleLength(title);
		if(titleOK == 2){
			return 2;
		}
		if(titleOK == 3){
			return 3;
		}
		boolean titleC = FilterCharsUtil.containsFilterChars(title);
		if(titleC){
			return 4;
		}
		return 1;
	}
	
	/**
	 * 验证article content
	 * @return 1:正常；2字符太少；3字符太多;4含有非法字符
	 */
	public int validateArticleContent(String content){
		int titleOK = KLGUtil.checkArticleContentLength(content);
		if(titleOK == 2){
			return 2;
		}
		if(titleOK == 3){
			return 3;
		}
		boolean titleC = FilterCharsUtil.containsFilterChars(content);
		if(titleC){
			return 4;
		}
		return 1;
	}
	

	/**
	 * 验证article.reply content
	 * @return 1:正常；2字符太少；3字符太多;4含有非法字符
	 */
	public int validateReplyContent(String content){
		int titleOK = KLGUtil.checkArticleReplyLength(content);
		if(titleOK == 2){
			return 2;
		}
		if(titleOK == 3){
			return 3;
		}
		boolean titleC = FilterCharsUtil.containsFilterChars(content);
		if(titleC){
			return 4;
		}
		return 1;
	}
}
